﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SubForum.DataAccess;
using SubForum.Web.Services.Interfaces;
using System.Web.Security;
using System.Transactions;
using SubForum.ObjectModel.Users;

namespace SubForum.Web.Services
{
    public class AccountMembershipService : IMembershipService
    {
        private MembershipProvider _provider;


        public DataService DataService
        {
            get;
            private set;
        }

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
            DataService = DataAccessManager.GetDataAccessService();
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public bool ValidateUser(string userName, string password)
        {
            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(MemberUser newUser)
        {
            MembershipCreateStatus status;

            //using (TransactionScope t = new TransactionScope())
            //{

                _provider.CreateUser(newUser.UserName, newUser.Password, newUser.Email, null, null, true, null, out status);

                // Add to local user profile tables
                DataService.InsertUserProfile(new List<MemberUser>() { newUser });

            //    t.Complete();

            //}
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
            return currentUser.ChangePassword(oldPassword, newPassword);
        }
    }
}